package com.lcx.client;

import com.lcx.encoder.RpcDecoder;
import com.lcx.encoder.RpcEncoder;
import com.lcx.handler.UserServiceHandler;
import com.lcx.request.RpcRequest;
import com.lcx.serializer.JSONSerializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements IUserService {


    @Override
    public String sayHello(String msg) {
        Random random = new Random();
        int millis = random.nextInt(200);
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("接到请求:" + msg + ", 服务端随机sleep:" + millis + "ms");
        return msg;
    }


    //创建一个启动服务器
    public static void startServer(String ip,int port){
        //1、创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2、创建服务器启动引导类
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3、配置启动引导对象
        serverBootstrap.group(bossGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        // 心跳检测
                        pipeline.addLast(new IdleStateHandler(0, 0, 5, TimeUnit.SECONDS));
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new UserServiceHandler());
                    }
                });
        try {
            //4、绑定端口
            ChannelFuture sync = serverBootstrap.bind(ip,port).sync();
            //注册到zk
            //持久节点
            String path = "/lcx-rpc/com.lcx.client.IUserService/provider";
            //创建连接
            CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                    .connectString("127.0.0.1:2181")
                    .retryPolicy(new RetryNTimes(1, 1000))
                    .connectionTimeoutMs(5000)
                    .sessionTimeoutMs(5000).build();
            curatorFramework.start();
            //创建永久节点
            if (curatorFramework.checkExists().forPath(path) == null){
                System.out.println("创建持久节点成功");
                curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path);
            }
            //创建临时节点
            String path2 = path + "/"+ip+":"+port;
            if (curatorFramework.checkExists().forPath(path2) == null){
                curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path2);
            }
            sync.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
